package qc.module.platform.mapper;

import org.apache.commons.lang3.StringUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
import qc.common.core.enums.ResourceStatusFlagEnum;
import qc.module.platform.dto.role.RoleDto;
import qc.module.platform.entity.QcRoles;

import java.util.List;

/**
 * RolesMapper
 *
 * @author QuCheng Tech
 * @create 2023/02/08
 */
@Mapper
public interface RolesMapper {
    RolesMapper MAPPER = Mappers.getMapper(RolesMapper.class);

    @Mapping(target = "pcode" , source = "projectcode")
    @Mapping(target = "flag", source = "flag.index")
    RoleDto toDto(QcRoles en);

    List<RoleDto> toDtoList(List<QcRoles> list);

    @Mapping(target = "projectcode" , source = "pcode")
    @Mapping(target = "flag", ignore = true)
    QcRoles toEntity(RoleDto dto);

    //转化为枚举类型字段
    default ResourceStatusFlagEnum toEnum(Integer flag){
        for (ResourceStatusFlagEnum eu : ResourceStatusFlagEnum.values()){
            if (eu.getIndex()==flag){
                return eu;
            }
        }
        return null;
    }

    /**
     * DTO转换为Entity
     *
     * @param dto 新增DTO
     * @return Entity
     * @author QuCheng Tech
     * @since 2023/6/26
     */
    default QcRoles RolesDtoToEntity(RoleDto dto) {
        //DTO转换为Entity
        QcRoles en = RolesMapper.MAPPER.toEntity(dto);

        //处理标记，非空时进行转换，空值时使用默认
        Integer flag = null;
        if (!StringUtils.isBlank(dto.getFlag())) {
            try {
                flag = Integer.parseInt(dto.getFlag());
            } catch (NumberFormatException exception) {
                //转换错误不处理，使用默认状态
            }
        }
        en.setFlag(getResourceStatusFlagEnum(flag));

        return en;
    }

    static ResourceStatusFlagEnum getResourceStatusFlagEnum(Integer index) {
        if (index != null && index > 0x0) {
            for (ResourceStatusFlagEnum item : ResourceStatusFlagEnum.values()) {
                if (item.getIndex() == index) {//判断序号使用getIndex，判断内容使用getName
                    return item;
                }
            }
        }
        return ResourceStatusFlagEnum.NORMAL;
    }
}
